<template>
	<view class="importWellet" :config="config" :change:config="renderjs.getConfig">
		<HeaderBar title="导入方式" showBack backgroundColor="#F6F6F6" fixed>
			<template #right>
				<!-- 			<image src="/static/images/login/scanning.png" mode="widthFix" style="width: 54upx;" @tap="scanQRCode">
				</image> -->
			</template>
		</HeaderBar>
		<view class="navTab">
			<view class="navLeft" :class="{'active':active==1}" @tap="tabNav(1)">
				助记词
			</view>
			<view class="navCenter" :class="{'active':active==3}" @tap="tabNav(3)">
				私钥
			</view>
			<!-- <view class="navRight" :class="{'active':active==3}" @tap="tabNav(3)">
				Keystore
			</view> -->
		</view>
		<view class="contentBox">
			<view class="scroll-Y">
				<view class="textarea_box">
					<textarea :placeholder="placeholderText" placeholder-style="color: #B2B2B2;font-size:24upx"
						class="textarea" v-model="textarea" placeholder-class="placeholder" />
					<view class="controls">
						<view class="paste" @tap="pasteText">
							粘贴
						</view>
						<!-- <view class="keypal" v-show="active!=3">
							KeyPal Card
						</view> -->
					</view>
				</view>
				<!-- <view class="model">
					<view class="">
						高级模式
						<text class="iconfont icon-youjiantou"></text>
					</view>
				</view> -->
				<view class="" v-if="!isOneAddress">
					<view class="form-item">
						<view class="title">设置钱包名</view>
						<view class="iptStyle name-ipt">
							<input class="input" name="input" v-model="name" :placeholder="placeholderName"
								placeholder-class="placeholder" maxlength="10" />
						</view>
					</view>
					<view class="form-item">
						<view class="title f28">设置密码</view>
						<view class="iptStyle pass-ipt">
							<input class="input" :password="showPassword" v-model="password" name="input"
								placeholder="密码不少于8位数(数字字母符号至少两种)" placeholder-style="color: #B2B2B2;font-size:24upx" />
							<uni-icons :type="showPassword?'eye':'eye-slash'" size="16" color="#368521"
								@click="changePassword"></uni-icons>
						</view>
						<view class="iptStyle confirm-pass-ipt">
							<input class="input" :password="showrePassword" v-model="rePassword" name="input" placeholder="确认密码"
								placeholder-style="color: #B2B2B2;font-size:24upx" />
							<uni-icons :type="showrePassword?'eye':'eye-slash'" size="16" color="#368521"
								@click="changerePassword"></uni-icons>
						</view>
					</view>
					<view class="form-item">
						<view class="title f28">提示信息</view>
						<view class="iptStyle name-ipt">
							<input class="input" name="input" v-model="passwordTilp" placeholder="密码提示信息（可不填)"
								placeholder-style="color: #B2B2B2;font-size:24upx" />
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="btn_box">
			<label class="protocol">
				<view class="raido-box" @tap="toggleButton">
					<image src="../../static/images/login/radio-check.png" mode="" class="raido" v-if="checked">
					</image>
					<image src="../../static/images/login/radio.png" mode="" class="raido" v-else></image>
				</view>
				<view class="tilp">
					我已仔细阅读并同意<text>《<text class="text" @tap="protocol">用户协议</text>》</text>
				</view>
			</label>
			<view class="btn" v-if="active==1" :class="{'disabled':checked}" :data-password="password"
				:data-rePassword="rePassword" :data-checked="checked" :data-isOneAddress="isOneAddress"
				:data-mnemonic="textarea" @tap="renderjs.getMnemoic">
				导入钱包
			</view>
			<view class="btn" v-if="active==3" :class="{'disabled':checked}" :data-password="password"
				:data-rePassword="rePassword" :data-checked="checked" :data-isOneAddress="isOneAddress"
				:data-privateKey="textarea" @tap="renderjs.getPrivateKey">
				导入钱包
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				active: 1,
				checked: false,
				config: {},
				textarea: "",
				name: "",
				isOneAddress: true,
				password: "",
				rePassword: "",
				passwordTilp: "",
				walletList: [],
				showPassword: true,
				showrePassword: true,
			};
		},
		watch: {
			config(newValue) {
				this.active = this.config.importMethod
			}
		},
		onLoad(options) {
			const configStr = options.configStr || '';
			try {
				// 解码并反序列化 JSON 字符串
				const config = JSON.parse(decodeURIComponent(configStr));
				this.config = config
				this.active = this.config.importMethod
			} catch (error) {}
			uni.$db.select('list', {
				from: 'addressList',
				select: ['address', 'password', 'passwordTilp', 'chainId'],
			}).then(res => {
				this.walletList = res
				if (res.length > 0) {
					this.isOneAddress = false
				} else {
					this.name = this.config.name
				}
			})
		},
		computed: {
			placeholderText() {
				if (this.active == 1) {
					return '请按顺序输入助记词，并使用空格分隔'
				} else if (this.active == 3) {
					return '请输入明文私钥或者扫描私钥二维码，请注意区分大小写'
				} else if (this.active == 4) {
					return '直接复制粘贴Keystore文件内容至输入框。或者通过生产 Keystore内容的二维码，扫描录入'
				}
			},
			chainId() {
				return this.$store.getters.getChainId;
			},
			allchains() {
				return this.$store.getters.getAllchains;
			},
			placeholderName() {
				return this.isOneAddress ? this.config.chainName + "-1" : this.config.name
			},
			tokenInfo() {
				const chainInfo = this.allchains.find((item) => item.chainId == this.config.chainId)
				const info = chainInfo.coin.find((item) => item.contract == this.$config
					.defaultAddress)
				return info
			},
		},
		methods: {
			changePassword() {
				this.showPassword = !this.showPassword;
			},
			changerePassword() {
				this.showrePassword = !this.showrePassword;
			},
			protocol() {
				uni.navigateTo({
					url: `/pages/protocol/protocol?id=3&title=用户协议`
				})
			},
			importWallet(wallet) {
				if (this.walletList.some(item => item.address == wallet.address && this.config.chainId == item.chainId)) {
					return this.toast('该地址已经存在')
				}
				let data = {
					address: wallet.address,
					privateKey: wallet.privateKey,
					mnemonics: wallet.wordlist,
					chainType: this.config.chainType,
					chainName: this.config.chainName,
					chainId: this.config.chainId,
					name: this.name || this.placeholderName,
					password: this.config.password ? this.config.password : this.password,
					passwordTilp: this.config.passwordTilp ? this.config.passwordTilp : this.passwordTilp,
					importMethod: this.config.importMethod
				}
				let token = {
					address: wallet.address,
					chainType: this.config.chainType,
					chainName: this.config.chainName,
					chainId: this.config.chainId,
					tokenaddress: this.$config.defaultAddress,
					tokenname: this.tokenInfo.name,
					tokenimg: "",
					tokennum: "0",
					tokendemail: this.tokenInfo.decimal,
					tokensymbol: this.tokenInfo.symbol,
					tokenprice: "1",
				}
				uni.$db.insert('list', 'choinList', token).then((res) => {
					uni.$db.insert('list', 'addressList', data).then((res) => {
						this.$store.commit('setAddress', wallet.address);
						this.$store.commit('setChainId', this.config.chainId);
						let rpclist = uni.getStorageSync('rpclist') || [];
						const foundChain = rpclist.find(chain => chain.chainId == this.config.chainId);
						this.$store.commit('setRpc', foundChain?.defultRPC);
						this.$updateWalletInfo()
						uni.switchTab({
							url: '/pages/index/index', // 这里的路径是 tabBar 页面在项目中的路径
							success() {},
							fail(err) {}
						});
					}).catch((err) => {
						return this.toast('钱包导入失败，请退出重新导入')
					});
				}).catch((err) => {
					return this.toast('钱包导入失败，请退出重新导入')
				});

			},
			pasteText() {
				uni.getClipboardData({
					success: (res) => {
						this.textarea = res.data;
					},
					fail() {}
				});
			},
			// scanQRCode() {
			// 	uni.scanCode({
			// 		success: (res) => {
			// 			this.textarea = res.result;
			// 		},
			// 		fail: (err) => {
			// 			// 扫描失败的回调
			// 		}
			// 	});
			// },
			toggleButton() {
				this.checked = !this.checked;
			},
			tabClick() {
				this.tabIndex = !this.tabIndex
			},
			tabNav(num) {
				this.active = num;
				this.textarea = ''
			},
			look() {
				this.isShow = !this.isShow
			},
			toast(msg) {
				uni.showToast({
					title: msg,
					position: "bottom",
					icon: 'none'
				});
			}
		}
	}
</script>

<script module="renderjs" lang="renderjs">
	export default {
		data() {
			return {
				config: {}
			}
		},
		mounted() {
			const chainType = this.config.chainType
			let scriptSrc = chainType === "ETH" ? 'static/script/ethers-5.2.umd.min.js' : 'static/script/newTronWeb.js';
			let script = document.createElement('script');
			script.src = scriptSrc;
			script.async = true;
			document.head.appendChild(script);
		},
		methods: {
			getConfig(newValue) {
				if (newValue) {
					this.config = newValue;
				}
			},
			//密码验证
			validatePassword(password) {
				const hasUpperCase = /[A-Z]/.test(password); // 是否包含大写字母
				const hasLowerCase = /[a-z]/.test(password); // 是否包含小写字母
				const hasNumbers = /\d/.test(password); // 是否包含数字
				const hasSpecialChars = /[!@#$%^&*(),.?":{}|<>]/.test(password); // 是否包含特殊字符
				const hasNoChineseChars = !/[\u4e00-\u9fa5]/.test(password); // 是否不包含汉字

				const conditionsMet = [hasUpperCase, hasLowerCase, hasNumbers, hasSpecialChars].filter(Boolean).length >=
					2;

				return password.length >= 8 && conditionsMet && hasNoChineseChars;
			},
			async getMnemoic(e) {
				if (!e.currentTarget.dataset.isOneAddress) {
					if (!e.currentTarget.dataset.password) {
						return this.$ownerInstance.callMethod('toast', '请输入钱包密码');
					}
					if (!this.validatePassword(e.currentTarget.dataset.password)) {
						return this.$ownerInstance.callMethod('toast', '密码格式有误');
					}
					if (e.currentTarget.dataset.rePassword != e.currentTarget.dataset.password) {
						return this.$ownerInstance.callMethod('toast', '密码不一致');
					}
				}


				if (!e.currentTarget.dataset.checked) {
					return this.$ownerInstance.callMethod('toast', '请阅读并同意协议');
				}
				let info
				let mnemonic = e.currentTarget.dataset.mnemonic
				if (!mnemonic) {
					this.$ownerInstance.callMethod('toast', "请输入助记词");
					return
				}

				if (this.config.chainType === "ETH") {
					try {
						const wallet = await new ethers.Wallet.fromMnemonic(mnemonic)
						let address = wallet.address
						let wordlist = mnemonic.replace(/ /g, ',')
						let privateKey = wallet.privateKey
						info = {
							address,
							privateKey,
							wordlist
						}
					} catch (e) {
						return this.$ownerInstance.callMethod('toast', '助记词有误');
					}
				} else if (this.config.chainType === "TRON") {
					try {
						let wallet = await TronWeb.TronWeb.fromMnemonic(mnemonic)
						let address = wallet.address
						let wordlist = mnemonic.replace(/ /g, ',')
						let privateKey = wallet.privateKey.slice(2)
						info = {
							address,
							privateKey,
							wordlist
						}
					} catch (e) {
						return this.$ownerInstance.callMethod('toast', '助记词有误');
					}

				}

				this.$ownerInstance.callMethod('importWallet', info);

			},
			async getPrivateKey(e) {
				if (!e.currentTarget.dataset.isOneAddress) {
					if (!e.currentTarget.dataset.password) {
						return this.$ownerInstance.callMethod('toast', '请输入钱包密码');
					}
					if (!this.validatePassword(e.currentTarget.dataset.password)) {
						return this.$ownerInstance.callMethod('toast', '密码格式有误');
					}
					if (e.currentTarget.dataset.rePassword != e.currentTarget.dataset.password) {
						return this.$ownerInstance.callMethod('toast', '密码不一致');
					}
				}
				if (!e.currentTarget.dataset.checked) {
					return this.$ownerInstance.callMethod('toast', '请阅读并同意协议');
				}
				let info
				let privateKey = e.currentTarget.dataset.privateKey
				if (!privateKey) {
					this.$ownerInstance.callMethod('toast', "请输入私钥");
					return
				}
				if (this.config.chainType === "ETH") {
					try {
						const wallet = new ethers.Wallet(privateKey)
						let address = wallet.address
						info = {
							address,
							privateKey: privateKey,
							wordlist: "",
						}
					} catch {
						this.$ownerInstance.callMethod('toast', '无效私钥');
					}

				} else if (this.config.chainType === "TRON") {
					const wallet = TronWeb.TronWeb.address.fromPrivateKey(privateKey)
					if (!wallet) {
						this.$ownerInstance.callMethod('toast', '无效私钥');
						return
					}
					info = {
						address: wallet,
						wordlist: '',
						privateKey,
					}
				}
				this.$ownerInstance.callMethod('importWallet', info);
			}
		},
	}
</script>

<style lang="scss" scoped>
	@import "/static/iconfont/iconfont.css";

	.importWellet {
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		background: #F6F6F6;

		.placeholder {
			color: #B2B2B2;
			font-size: 26upx;
			font-weight: bold;
		}

		.navTab {
			margin: 0 40upx;
			background: #E9EAEC;
			padding: 8upx 22upx;
			text-align: center;
			display: flex;
			font-size: 26upx;
			border-radius: 20upx;

			.navLeft {
				flex: 1;
				line-height: 72upx;
			}

			.navCenter {
				flex: 1;
				line-height: 72upx;
			}

			.navRight {
				flex: 1;
				line-height: 72upx;
			}

			.active {
				background: #FFF;
				border-radius: 20upx;
			}
		}

		.contentBox {
			flex: 1;
			padding: 30upx 40upx;
			display: flex;
			flex-direction: column;

			.scroll-Y {

				::-webkit-scrollbar {
					width: 0;
					height: 0;
				}

				-ms-overflow-style: none;
				/* 适用于 IE、Edge */
				scrollbar-width: none;
				/* 适用于 Firefox */
				height: 100%;

				.textarea_box {

					height: 224upx;
					background: #FFF;
					border-radius: 20upx;
					padding: 24upx 26upx;

					.textarea {
						width: 100%;
						height: 188upx;
						box-sizing: border-box;
					}


					.controls {
						display: flex;
						font-size: 26upx;
						line-height: 36upx;
						color: #368521;
						font-weight: 400;
						flex-direction: row-reverse;

						.paste {
							padding: 0 20upx;
						}

						.keypal {
							padding: 0 20upx;
							border-right: 1px solid #D8D8D8;
						}
					}
				}

				.model {
					margin-top: 36upx;
					text-align: right;
					color: #8E8E8E;
					font-size: 26upx;
					font-weight: 400;
				}

				.form-item {
					margin-top: 30upx;

					.title {
						font-size: 30upx;
						color: #3D3D3D;
					}

					.f28 {
						font-size: 28upx;
					}

					.iptStyle {
						border-radius: 20upx;
						background-color: #FFFFFF;

						.input {
							padding: 26upx 24upx;
							font-size: 26upx;
							flex: 1;
						}
					}

					.name-ipt {
						margin-top: 20upx;
					}

					.pass-ipt {
						margin-top: 26upx;
						display: flex;
						align-items: center;
						.uni-icons{
							margin: 0 20upx;
						}
					}
					.confirm-pass-ipt {
						margin-top: 12upx;
						display: flex;
						align-items: center;
						.uni-icons{
							margin: 0 20upx;
						}
					}

					.confirm-pass-ipt {
						margin-top: 12upx;
					}

				}
			}
		}

		.btn_box {
			padding: 0 40upx 90upx;

			.protocol {
				display: flex;
				align-items: center;

				.raido-box {
					display: flex;

					.raido {
						width: 32upx;
						height: 32upx;
					}
				}

				.tilp {
					color: #8E8E8E;
					font-size: 26upx;
					margin-left: 10upx;

					.text {
						color: #297814;
					}
				}
			}

			.btn {
				font-size: 26upx;
				color: #F6F6F6;
				line-height: 88upx;
				background: linear-gradient(180deg, #CEF3D3 100%, #297814 61%);
				border-radius: 10upx;
				text-align: center;
				margin-top: 30upx;
			}

			.disabled {
				background: linear-gradient(180deg, #A9E993 0%, #368321 100%);
			}
		}
	}
</style>